package com.atguigu.gmall.serviceutil.Interceptor;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/9/10 0:03
 */
@Component
public class AppFeignInterceptor implements RequestInterceptor {
    //可以对请求参数进行处理
    @Override
    public void apply(RequestTemplate template) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            throw new GmallException(ResultCodeEnum.REQUEST_NULL_ASYNC_ERROR);
        }

        HttpServletRequest request = requestAttributes.getRequest();

        String userId = request.getHeader("UserId");
        if (!StringUtils.isEmpty(userId)) {
            template.header("UserId", userId);
        }
        String userTempId = request.getHeader("UserTempId");
        if (!StringUtils.isEmpty(userTempId)){
            template.header("UserTempId", userTempId);
        }


    }
}
